package controllers

import "LoginTemplate/models"

type ClassifyController struct {
	BaseController
}

type Classify struct {
	ID           int    `json:"id"`
	ClassifyName string `json:"classify_name"`
	ClassifyType int    `json:"classify_type"`
	IsDe         int    `json:"is_de"`
}

// 添加分类
func (u *ClassifyController) InsertClassify() {
	var classify Classify
	err := u.ShouldBind(&classify)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into classify ( classify_name,classify_type ) values ( ? , ? )"
	tx := models.DB.Debug().Exec(sql, classify.ClassifyName, classify.ClassifyType)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改分类
func (u *ClassifyController) UpdateClassify() {
	var classify Classify
	err := u.ShouldBind(&classify)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update classify set classify_name = ?,classify_type = ?,is_de = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, classify.ClassifyName, classify.ClassifyType, classify.IsDe, classify.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type ClassifyData struct {
	Code        int        `json:"code"`
	Msg         string     `json:"msg"`
	Data        []Classify `json:"data"`
	Sum         int        `json:"sum"`         //总页数
	CurrentPage int        `json:"currentPage"` //当前页
	TotalNumber int        `json:"totalNumber"` //总条数
}

// 查询分类
func (u *ClassifyController) SelectClassify() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var classify []Classify
	sql := "select * from classify where is_de = 0 limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&classify)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM classify"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from classify"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata ClassifyData
	picturedata.Code = 200
	picturedata.Data = classify
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
